/*
 * SPI.c
 *
 * 
 * 
 */ 

#include <avr/io.h>

unsigned char spi_slave=0;

void	SPI_Init()
{
	// Init SPI
	// SCK, MOSI and SS outputs
	// MISO input
	DDRB = 0b10110000;
	
	// Enable SPI
	// SPI Master
	// SPI clock = fosc/16
	// CPHA = 1
	SPCR = 0b01010101;
	
}

void SPI_Start(unsigned char slave)
{
	// Activate RTC chip select
	spi_slave=slave;
	PORTB |= (1<<spi_slave);	
}

void SPI_End(unsigned char slave)
{
	// Deactivate RTC chip select  
	PORTB &= ~(1<<spi_slave);
}
unsigned char	SPI_Read()
{	
	unsigned char dummy;
	    
	// Send "dummy byte" (to generate 8 clock periods)
	SPDR = 0; 
	// Await dummy sent
	while(!(SPSR&(1<<SPIF)))
	{}
	// Clear SPIF flag  
	dummy = SPSR;
	dummy = SPDR;
	
	return(SPDR);
}
void	SPI_Write(unsigned char byte)
{
	unsigned char dummy;	

	// Send address
	SPDR = byte; 
	// Await address sent
	while(!(SPSR&(1<<SPIF)))
	{}
	// Clear SPIF flag
	dummy = SPSR;
	dummy = SPDR;
  
}
